<?php
namespace app\index\model\wanlshop;

use app\common\model\UserGroup;
use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'wanlshop_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'flag_text',
        'stock_text',
        'specs_text',
        'distribution_text',
        'activity_text',
        'status_text',
        'hot_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    
    public function getFlagList()
    {
        return ['hot' => __('Flag hot'), 'index' => __('Flag index'), 'recommend' => __('Flag recommend')];
    }

    public function getStockList()
    {
        return ['porder' => __('Stock porder'), 'payment' => __('Stock payment')];
    }

    public function getSpecsList()
    {
        return ['single' => __('Specs single'), 'multi' => __('Specs multi')];
    }

    public function getDistributionList()
    {
        return ['true' => __('Distribution true'), 'false' => __('Distribution false')];
    }

    public function getActivityList()
    {
        return ['true' => __('Activity true'), 'false' => __('Activity false')];
    }

    //

    public function gethotList()
    {
        return ['yes' => __('是'), 'hidden' => __('否')];
    }

    public function getStatusList()
    {
        return ['normal' => __('上架'), 'hidden' => __('下架')];
    }

    public function getPricingList(){
        return ['no'=>'自定义','ratio'=>'动态比例','fixed'=>'动态固定金额'];
    }


    public function getFlagTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['flag']) ? $data['flag'] : '');
        $valueArr = explode(',', $value);
        $list = $this->getFlagList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }


    public function getStockTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['stock']) ? $data['stock'] : '');
        $list = $this->getStockList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSpecsTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['specs']) ? $data['specs'] : '');
        $list = $this->getSpecsList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDistributionTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['distribution']) ? $data['distribution'] : '');
        $list = $this->getDistributionList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getActivityTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['activity']) ? $data['activity'] : '');
        $list = $this->getActivityList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getHotTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['hot']) ? $data['hot'] : '');
        $list = $this->gethotList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setFlagAttr($value)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

	public function category()
	{
	    return $this->belongsTo('app\index\model\wanlshop\Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
	}
	
	
	public function shopsort()
	{
	    return $this->belongsTo('app\index\model\wanlshop\ShopSort', 'shop_category_id', 'id', [], 'LEFT')->setEagerlyType(0);
	}

    public function brand()
    {
        return $this->belongsTo('app\index\model\wanlshop\Brand', 'brand_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function sku(){
        return $this->hasMany('app\index\model\wanlshop\GoodsSku','goods_id','id');
    }

	//同步更新商品sku调价
    public function updateGoodsSku($goods_id){
        \think\Log::write('准备执行--updateGoodsSku--');
        Db::startTrans();
        $shopGoods = $this->get($goods_id);
        $shop = Shop::get($shopGoods['shop_id']);
        $platformGoods = $this->get($shopGoods['parent_id'])->toArray();
        $platformGoodsId = $platformGoods['id'];
        if(!$platformGoods){
            return false;
        }
        unset(
            $platformGoods['id'],
            $platformGoods['parent_id'],
            $platformGoods['shop_id'],
            $platformGoods['shop_category_id'],
            $platformGoods['freight_id'],
            $platformGoods['grounding'],
            $platformGoods['pricing'],
            $platformGoods['pricing_base'],
            $platformGoods['createtime']);
        $shopGoods->allowField(true)->save($platformGoods);

        $platformSku = model('app\index\model\wanlshop\GoodsSku')
            ->where(['goods_id' => $platformGoodsId, 'state' => 0])
            ->field('id,difference,difference_en,price,market_price,supply_price,group_price,stock,weigh,sn,sales,state,sort,rule_id')
            ->order('sort asc')
            ->select();
        // 将商家商品sku标记为旧版数据
        model('app\index\model\wanlshop\GoodsSku')->where([
            'goods_id' => $goods_id,
            'state' => 0
        ])->update(['state'=>1]);
        $pricingBase = json_decode($shopGoods['pricing_base']);
        $pricingBase = $pricingBase ? array_column($pricingBase,'base','group_id') : '';
        $sku = [];
        foreach ($platformSku as $value){
            $skuRow = model('app\index\model\wanlshop\GoodsSku')->where([
                'goods_id'   => $goods_id,
                'difference' => $value['difference'],
            ])->order('createtime desc')->find();
            $group_price = $user_group_price = [];
            $skuPrice = $value['price'];
            $group_price = is_array($value['group_price']) ? $value['group_price'] :  json_decode($value['group_price'],true);
            $supply_price = $value['supply_price'];
            foreach ($group_price as $group){
                if($shop['group_id'] == $group['group_id']){
                    $supply_price = $group['price'];
                }
            }

            if($pricingBase){
                foreach ($pricingBase as $group_id => $base){
                    if($shopGoods['pricing'] !== 'no'){
                        if($group_id == 0){
                            $skuPrice = $shopGoods['pricing'] == 'ratio' ? sprintf("%.2f",$supply_price * $base) : sprintf("%.2f",$supply_price + $base);
                        }else{
                            $user_group_price[] = [
                                'group_id' => $group_id,
                                'price'    => $shopGoods['pricing'] == 'ratio' ? sprintf("%.2f",$supply_price * $base) : sprintf("%.2f",$supply_price + $base)
                            ];
                        }
                    }
                }
            }else{
                $userGroup = UserGroup::where('status','normal')->select();
                foreach ($userGroup as $val){
                    $user_group_price[] = [
                        'group_id' => $val['id'],
                        'price' => bcmul($supply_price,1.2,2),
                    ];
                }
            }
            $user_group_price = is_array($user_group_price) ? json_encode($user_group_price) : $user_group_price;
            if($skuRow){
                $sku[] = [
                    'id'           => $skuRow['id'],
                    'goods_id'     => $goods_id,
                    'difference'   => $value['difference'],
                    'difference_en'=> $value['difference_en'],
                    'market_price' => $value['market_price'],
                    'price'        => $skuPrice,
                    'supply_price' => $supply_price,
                    'group_price'  => $user_group_price,
                    'stock'        => $value['stock'],
                    'sort'         => $value['sort'],
                    'weigh'        => $value['weigh'],
                    'sn'           => $value['sn'],
                    'rule_id'      => $value['rule_id'],
                    'state'        => 0
                ];
            }else{
                $sku[] = [
                    'goods_id'     => $goods_id,
                    'difference'   => $value['difference'],
                    'difference_en'=> $value['difference_en'],
                    'market_price' => $value['market_price'],
                    'price'        => $skuPrice,
                    'supply_price' => $supply_price,
                    'group_price'  => $user_group_price,
                    'stock'        => $value['stock'],
                    'sort'         => $value['sort'],
                    'weigh'        => $value['weigh'],
                    'sn'           => $value['sn'],
                    'rule_id'      => $value['rule_id'],
                    'state'        => 0
                ];
            }

        }
        model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($sku);
        // 删除原来数据,重新写入SPU

        model('app\index\model\wanlshop\GoodsSpu')
            ->where('goods_id','in',$goods_id)
            ->delete();
        $platformSpu = model('app\index\model\wanlshop\GoodsSpu')
            ->where(['goods_id' => $platformGoodsId])
            ->select();
        $spu = [];
        foreach ($platformSpu as $value){
            $spu[] = [
                'goods_id' => $goods_id,
                'name' => $value['name'],
                'name_en' => $value['name_en'],
                'item' => $value['item'],
                'item_en' => $value['item_en'],
            ];
        }
        model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu);
        Db::commit();
    }
	
}
